<template>
  <div class="search-div">
    <!-- 搜索表单 -->
    <el-form label-width="70px" size="small" style="display:flex">
      <el-form-item label="角色名称">
        <el-input v-model="queryDto.roleName"
                  style="width: 90%"
                  placeholder="角色名称"
        ></el-input>
      </el-form-item>
      <el-row>
        <el-button type="primary" size="small" @click="searchSysRole">
          搜索
        </el-button>
        <el-button size="small" @click="reset">重置</el-button>
      </el-row>
    </el-form>

    <!-- 添加按钮 -->
    <div class="tools-div">
      <el-button type="success" size="small" @click="add">添 加</el-button>
    </div>

    <!--- 角色表格数据 -->
    <el-table :data="list" style="width: 100%">
      <el-table-column prop="roleName" label="角色名称" width="180" />
      <el-table-column prop="roleCode" label="角色code" width="180" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" align="center" width="280" #default="scope">
        <el-button type="primary" size="small" @click="edit(scope.row)">修改</el-button>
        <el-button type="danger" size="small" @click="delSysRole(scope.row)">删除</el-button>
        <el-button type="warning" size="small" @click="showAssignMenu(scope.row)">分配菜单</el-button>
      </el-table-column>
    </el-table>

    <!-- 分配菜单的对话框
    // tree组件添加ref属性，后期方便进行tree组件对象的获取
    -->
    <el-dialog v-model="dialogMenuTrre" title="分配菜单" width="40%">
      <el-form label-width="80px">
        <el-tree
          :data="sysMenuTreeList"
          ref="tree"
          show-checkbox
          :check-strictly ="true"
          :default-expand-all="false"
          :check-on-click-node="true"
          :default-checked-keys ="defaultCheckedKeys"
          node-key="id"
          :props="defaultProps"
        />
        <el-form-item>
          <el-button type="primary" @click="menuTrreSubmit">提交</el-button>
          <el-button @click="dialogMenuTrre = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--分页条-->
    <el-pagination
      v-model:current-page="queryDto.pageNum"
      v-model:page-size="queryDto.pageSize"
      :page-sizes="[5, 10, 20]"
      @size-change="getFindByPage"
      @current-change="getFindByPage"
      layout="total, sizes, prev, pager, next"
      :total="total"
    />
  </div>

  <el-dialog v-model="dialogFormVisible" :title="dialogTitle">
    <el-form :model="sysRole">
      <el-form-item label="角色名称" style="width: 80%">
        <el-input v-model="sysRole.roleName" />
      </el-form-item>
      <el-form-item label="角色code" style="width: 80%">
        <el-input v-model="sysRole.roleCode" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script setup>
import { ref, onMounted,computed } from "vue";
import { findByPage, saveOrUpdate, batchDelete,findMenuIdsByRoleId ,assigningMenus} from "@/api/system/sys-role";
import { ElMessage ,ElMessageBox} from "element-plus";
import { findNodes } from "@/api/system/menu";

const list = ref([])
const tree = ref()
const defaultProps = {
  children: 'children',
  label: 'title',
}
const defaultCheckedKeys = ref([2,3,1]);
const dialogMenuTrre = ref(false);
// 分页条总记录数
let total = ref(0);
// 定义表格数据模型
let sysMenuTreeList = ref([]);
const dialogTitle = ref("");

const dialogFormVisible = ref(false);

const data = {
  pageNum: 1,
  pageSize: 10,
  roleName: ""
};

const queryDto = ref(data);

//表单数据模型
const defaultForm = {
  id: "",
  roleCode: "",
  roleName: ""
};
const sysRole = ref(defaultForm);   // 使用ref包裹该对象，使用reactive不方便进行重置

// 页面加载完毕以后请求后端接口获取数据
onMounted(() => {
  getFindByPage();
});


//搜索
const searchSysRole = async () => {
  getFindByPage();
};
//重置
const reset = () => {
  queryDto.value = {
    pageNum: 1,
    pageSize: 10,
    roleName: ""
  };
  getFindByPage();
};

//获取列表数据
const getFindByPage = async () => {
  const { data } = await findByPage(queryDto.value);
  list.value = data.records;
  total.value = data.total;
};

//添加按钮事件
const add = () => {
  dialogTitle.value = "添加角色";
  dialogFormVisible.value = true;
  sysRole.value.roleName = "";
  sysRole.value.roleCode = "";
  sysRole.value.id = "";
};
//修改按钮
const edit = async (row) => {
  dialogTitle.value = "修改角色";
  dialogFormVisible.value = true;
  sysRole.value = row;
};

//删除事件
const delSysRole = async (row) => {

  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const {code } = await batchDelete([row.id])
    if(code === 200) {
      ElMessage.success('删除成功')
      queryDto.value.pageNum = 1
      getFindByPage();
    }
  })
};

//修改或者新增
const submit = async () => {
  const { code } = await saveOrUpdate(sysRole.value);
  if (code === 200) {
    dialogFormVisible.value = false;
    getFindByPage();
    ElMessage.success("操作成功");
  }
};

const showAssignMenu = (row) => {
  dialogMenuTrre.value = true;
  getfindNodes()
  getfindMenuIdsByRoleId(row)
  sysRole.value = row
}

const menuTrreSubmit = async () => {
  const checkedNodes = tree.value.getCheckedNodes() ; // 获取选中的节点
  let array = []
  checkedNodes.map(node => {
     array.push(node.id)
  })
  let data = {
    roleId: sysRole.value.id,
    menuIdList: array
  }
  getAssigningMenus(data)
};

const getfindMenuIdsByRoleId = async (row) => {
  const {data} = await findMenuIdsByRoleId(row.id);
  defaultCheckedKeys.value = data;
}

const getfindNodes = async () =>{
  const {data} = await findNodes();
  sysMenuTreeList.value = data;
}

const getAssigningMenus = async (data) =>{
  const {code} = await assigningMenus(data);
  if (code === 200){
    ElMessage.success("操作成功");
    dialogMenuTrre.value = false;
  }

}
</script>

<style scoped>

.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

</style>